#!/usr/bin/python3
# -*- coding: utf-8 -*-

# @Time    : 2018/11/8 16:20
# @Author  : chester7cheng
# @Email   : 346835646@qq.com
# @File    : map_reduce.py
# @Software: PyCharm


# print(abs(10))
# print(abs)
# f = abs
# print(f)
# print(f(-10))
from functools import reduce


def add(x, y, f):
    return f(x) + f(y)


def f(x):
    return x * x


print(add(2, 3, f))

r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(r)
lr = list(r)
print(list(r))
print(lr)

ls = list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(ls)


def add(x, y):
    return x * 10 + y


print(reduce(add, [1, 3, 5, 7, 9]))
r = reduce(add, [1, 3, 5, 7, 9])
print(r)

DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}


def str2int(s):
    def fn(x, y):
        return x * 10 + y

    def char2num(str):
        return DIGITS[str]

    return reduce(fn, map(char2num, s))


print(str2int('9527'))


def str2int(s):
    def char2num(str):
        return DIGITS[str]

    return reduce(lambda x, y: x * 10 + y, map(char2num, s))


print(str2int('222'))


def normalize(name):
    result = ''
    name_len = len(name)
    for i in range(name_len):
        if i == 0:
            result += name[i].upper()
        else:
            result += name[i].lower()

    return result


L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)


def prod(L):
    def fn(x, y):
        return x * y

    return reduce(fn, L)


print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('测试成功!')
else:
    print('测试失败!')


def str2float(s):
    def fmap(s):
        return s

    def freduce1(x, y):
        z = int(x) * 10 + int(y)
        print(z)
        return z

    def freduce2(x, y):
        z = float(x) / 10 + float(y)
        print(z)
        return z

    l = list(map(fmap, s))
    index = l.index('.')
    l1 = l[0: index]
    print(l1)
    l2 = list(reversed(l[index + 1: len(l)]))
    print(l2)

    return reduce(freduce1, l1) + reduce(freduce2, l2) / 10


def str2float(s):
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    p = s.replace('.', '')

    def char2num(n):
        return DIGITS[n]

    return reduce(lambda x, y: 10 * x + y, map(char2num, p)) / pow(10, len(s) - 1 - s.index('.'))


print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('测试成功!')
else:
    print('测试失败!')
